import { changeGoodsNum, deleteGoods, getCartList } from '@/api/cart'
import { Toast } from 'vant'
export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    /**
     * 设置购物车列表
     *
     * @param state Vuex状态对象
     * @param newList 新的购物车列表
     * @returns 无返回值
     */
    setCartList (state, newList) {
      state.cartList = newList
    },
    /**
     * 切换商品的选中状态
     *
     * @param state 购物车状态对象
     * @param goodsId 商品ID
     * @returns 无返回值，直接修改state中的cartList
     */
    toggleCheck (state, goodsId) {
      // 在购物车列表中找到与给定 goodsId 相匹配的商品
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      // 将该商品的 isChecked 属性取反
      goods.isChecked = !goods.isChecked
    },
    selAll (state, flag) {
      state.cartList.forEach(item => { item.isChecked = flag })
    },
    changeGoodsNum (state, { goodsId, goodsNum }) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = goodsNum
    }
  },
  actions: {
    /**
     * 异步获取购物车列表并更新到上下文中
     *
     * @param context Vuex上下文对象
     * @returns 无返回值，但会更新上下文中购物车列表的状态
     */
    async getCartAction (context) {
      const { data } = await getCartList()
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', data.list)
    },
    async changeGoodsNumAction (context, obj) {
      const { goodsId, goodsNum, goodsSkuId } = obj
      context.commit('changeGoodsNum', { goodsId, goodsNum })
      // 修改后台数据
      const res = await changeGoodsNum(goodsId, goodsNum, goodsSkuId)
      console.log(res)
    },
    async delCartAction (context) {
      const cartIds = context.getters.selCartList?.map(item => item.id)
      // 删除购物车中的商品
      await deleteGoods(cartIds)
      Toast('删除成功')
      context.dispatch('getCartAction')
    }
  },
  getters: {
    // 购物车总数量
    cartTotal: state => state.cartList.reduce((sum, item) => sum + item.goods_num, 0),
    // 购物车中选中的商品列表
    selCartList: state => state.cartList.filter(item => item.isChecked),
    // 选中的商品的总数量
    selCount: (state, getters) => getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0),
    // 选中的的商品的总价格
    selPrice: (state, getters) => getters.selCartList.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0).toFixed(2),
    // 是否全部选中
    isAllChecked: state => state.cartList.every(item => item.isChecked)

  }

}
